
import api from '~/api/index.js'
import proxy from '~/proxy'
export default function ({ $axios, app }, inject) {
  $axios.defaults.baseURL = proxy.onlineIP
  $axios.defaults.withCredentials = true;
  $axios.onRequest((config) => {
    config.headers.common['Content-Type'] = 'application/json'
  })
  console.log(proxy.onlineIP)
  // 响应拦截器
  $axios.interceptors.response.use((response) => {
    if (response.data.code !== 2000) {
      // 状态码不是2000时，表示接口出错
      let msg = "";
      if (response.data.msg.length > 0 && typeof response.data.msg === "object") {
        for (const i in response.data.msg[0]) {
          msg = i + ": " + response.data.msg[0][i]
        }
      } else if (typeof response.data.msg === "object") {
        for (const i in response.data.msg) {
          msg = i + ": " + response.data.msg[i] + ";"
        }
        msg = msg.substring(0, msg.length - 1);
      } else {
        msg = response.data.msg
      }
      return Promise.reject(response)
    }
    return response.data
  }, (error) => {
    return Promise.reject(error)
  })
  $axios.onError((err) => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = '请求错误(400)';
          break;
        case 403:
          err.message = '拒绝访问(403)';
          break;
        case 404:
          err.message = '请求出错(404)';
          break;
        case 408:
          err.message = '请求超时(408)';
          break;
        case 500:
          err.message = '服务器错误(500)';
          break;
        case 501:
          err.message = '服务未实现(501)';
          break;
        case 502:
          err.message = '网络错误(502)';
          break;
        case 503:
          err.message = '服务不可用(503)';
          break;
        case 504:
          err.message = '网络超时(504)';
          break;
        case 505:
          err.message = 'HTTP版本不受支持(505)';
          break;
        default:
          err.message = `连接出错(${err.response.status})!`;
      }
      // Message({
      //     message: err.message,
      //     type: 'warning'
      // })
      return Promise.reject(err);
    }
    if (err.data) {
      return Promise.reject(err.data);
    }
    // Message({
    //     message: '连接服务器失败',
    //     type: 'warning'
    // })
    return Promise.reject(err);
  })
  // 将所有请求注入到服务器端
  const apis = api($axios)
  inject('api', apis)
}
